#!/usr/bin/env python
# 
# Copyright 2009 Tim Dedischew, released under the GPL v2
#
"""Pegasus Digital Pen flash to SVG tool"""

### NOT FINISHED YET
### temporary usage: ./flash2svg.py [file.bin] [zero-based page number] > theresults.svg


VERSION = "0.00"

import sys

# allow this to be run right out of the svn dir:
import os,sys
libsdir = os.path.realpath(os.getcwd() + '/../../src')
if os.path.isdir(libsdir) and os.path.isfile(libsdir + '/pegasus.py'):
	sys.path.insert(0, libsdir)
else:
	libsdir = os.path.realpath(os.getcwd() + '/src')
	if os.path.isdir(libsdir) and os.path.isfile(libsdir + '/pegasus.py'):
		sys.path.insert(0, libsdir)

from pegasus import depackable
if (sys.argv[1] == '-'):
	mem = sys.stdin
else:
	mem = file(sys.argv[1], "rb")
bin = mem.read()
assert not mem.read()
_NOTEHEADER = depackable('NOTEHEADER', 'a b c flags notenum total d e f g h i j addr', "<cccccccccccccc")
DATAXY = depackable('DATAXY', 'x y', "<hh")

def dump_bytes(bytes):
	return " ".join(hex(ord(b)) for b in bytes) + " "

def NOTEHEADER(bytes):
	tmp = _NOTEHEADER(bytes[:14])
	tmp = tmp._tmp._replace(tmp, addr=(ord(tmp.c)<<16) + (ord(tmp.b) <<8) + ord(tmp.a))
	return tmp

minx = miny = sys.maxint
maxx = maxy = -sys.maxint
svg = """<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="{sheight}" width="{swidth}"
  version="1.1" xmlns="http://www.w3.org/2000/svg">
  <desc>generated by pegtool -- flash2svg.py</desc>
<g transform="translate({xoff},{yoff}) scale({scale},{scale})" fill="none" stroke-width="1em" stroke="rgb(0, 0, 0)">
"""
i = 0
while (i < (len(bin)) and bin[i:3] != '\x00\x00\x00'):
	svg += "<!-- ni: %d / %d / %d -->\n" % (i, len(bin), len(bin)-i)
	#sys.stderr.write(dump_bytes(bin[i:i+14])+"\n")
	assert (len(bin)-i) >= 14
	tmp = NOTEHEADER(bin[i:])
	nn = str(ord(tmp.notenum) - 1)
	#sys.stderr.write("%s\n"%str(tmp))
 	i += 14
	data = bin[i:tmp.addr]
	i = tmp.addr

	if (not data):
		break

	svg += "\t<!-- Notenum: %s, len(data): %d -->\n" % (nn, len(data))

	if (nn != sys.argv[2]):
		svg += "\t<!-- skipped -->\n"
		continue

	def makepoly(points):
		global svg
		if (points):
			svg += '\t<polyline points="%s"></polyline>\n\n' % " ".join(points)

	points = []
	while data:
		xy = DATAXY(data[:4])
		data = data[4:]
		if (xy.y == -32768):
			# EOSTROKE handling
			makepoly(points)
			points = []
		else:
			if (xy.x < minx):
				minx = xy.x
			if (xy.y < miny):
				miny = xy.y
			if (xy.x > maxx):
				maxx = xy.x
			if (xy.y > maxy):
				maxy = xy.y
			points.append("%d,%d" % (xy.x,xy.y))
	makepoly(points)
	

svg += "</g></svg>"
svg = svg.replace("{minx}", str(minx))
svg = svg.replace("{miny}", str(miny))
svg = svg.replace("{maxx}", str(maxx))
svg = svg.replace("{maxy}", str(maxy))


#scale = (maxx-minx) / 6000.0 / 10.0 ## FIXME: not sure what the right math is here, but raw coords look like decimeters
#scale *= 50.0/100.0 # make smaller for testing with KDE svgdisplay
scale = 0.1
svg = svg.replace("{swidth}", str(scale*(maxx-minx)))
svg = svg.replace("{sheight}", str(scale*(maxy-miny)))
svg = svg.replace("{scale}", str(scale))
svg = svg.replace("{xoff}", str(-minx*scale))
svg = svg.replace("{yoff}", str(-miny*scale))
print svg
	#exit()
		
	
	
#print tmp
